package com.personal.android.general.thread;

import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by winter on 2015/9/22.
 *
 * @author winter
 */
public class DefaultThreadPool {

    protected ThreadPoolExecutor mThreadPoolExecutor;

    protected DefaultThreadPool(int poolSize) {
        mThreadPoolExecutor = new ThreadPoolExecutor(poolSize, poolSize, 0, TimeUnit.SECONDS
                , new LinkedBlockingDeque<Runnable>(), new DefaultThreadFactory());
    }

    protected DefaultThreadPool(int poolSize, int queueSize) {
        mThreadPoolExecutor = new ThreadPoolExecutor(poolSize, poolSize, 0, TimeUnit.SECONDS
                , new LinkedBlockingQueue<Runnable>(queueSize), new DefaultThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy());
    }

    public synchronized void execute(Runnable runnable) {
        mThreadPoolExecutor.execute(runnable);
    }

    private static final int AWAIT_TERMINATION_TIMEOUT = 10000;//ms

    /**
     * 关闭并取消在等待中的任务，尝试关闭正在执行的任务，无法关闭的等待完成，然后结束线程池
     *
     * @return 被取消的task
     * @throws InterruptedException InterruptedException
     */
    public synchronized List<Runnable> shutDownNowAndTermination() throws InterruptedException {
        List<Runnable> canceledTask = mThreadPoolExecutor.shutdownNow();
        mThreadPoolExecutor.awaitTermination(AWAIT_TERMINATION_TIMEOUT, TimeUnit.MILLISECONDS);
        return canceledTask;
    }

    /**
     * 关闭并等待任务结束，然后关闭结束线程池
     *
     * @throws InterruptedException InterruptedException
     */
    public synchronized void shutDownAndTermination() throws InterruptedException {
        mThreadPoolExecutor.shutdown();
        mThreadPoolExecutor.awaitTermination(AWAIT_TERMINATION_TIMEOUT, TimeUnit.MILLISECONDS);
    }

    /**
     * 是否关闭，关闭后不能加入新的任务
     *
     * @return true 表示关闭
     */
    public boolean isShutdown() {
        return mThreadPoolExecutor.isShutdown();
    }

    /**
     * 是否已经结束
     *
     * @return true 表示结束
     */
    public boolean isTerminated() {
        return mThreadPoolExecutor.isTerminated();
    }
}
